/**
 * Created by huotaol on 2017/4/27.
 */
import React, {Component} from "react";
import PropTypes from "prop-types";
import {
    Image,
    ScrollView,
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    TouchableWithoutFeedback,
    View
} from "react-native";
import CustomStyle from "../../../common/style/CustomStyle";
import {connect} from "react-redux";
import {Actions} from "react-native-router-flux";
import Modal from "react-native-modal";
import AreaSelect from "../../page/AreaSelect";
import DatePicker from "react-native-datepicker";
import Util from "../../main/Util";
import Toast from "react-native-root-toast";
import * as Url from "../../constant/Url";
import {request} from "../../../common/util/RequestUtil";
import Button from "../../components/Button";
import HelpList from "./component/HelpList";
import {callPhone} from "../../../common/util/Util.js";

class HelpLook extends Component {

    static propTypes = {
        carDetail: PropTypes.string
    };

    static defaultProps = {
        carDetail: ''
    };

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            isModalVisible: false,
            selectArea: props.selectArea,
            date: '',
            phone: Util.getUser().phone,
            verifyCode: '',
            requestingVerifyCode: false,
            carDetail: props.carDetail,
            checkedCarOfNumber: 0,
            searchNum: '',
        };
        this._subscribe = this._subscribe.bind(this);
        this._onCarDetailSelected = this._onCarDetailSelected.bind(this);
        this._fetchHelpLookInfo = this._fetchHelpLookInfo.bind(this);
    }

    componentDidMount() {
        this._fetchHelpLookInfo();
    }

    _getSoldCarInfo() {
        const detail = this.state.carDetail;
        return detail ? detail : '车辆信息';
    }

    render() {
        return (
            <View
                style={{backgroundColor: '#7B4000',}}
            >
                <ScrollView
                >
                    <Image source={require('../../../img/helplook/background.png')}
                           style={{
                               width: CustomStyle.screenWidth, height: CustomStyle.getActualSizeInVertical(460),
                               paddingBottom: CustomStyle.getActualSizeInVertical(20),
                           }}>
                        <View style={{
                            height: CustomStyle.getActualSizeInVertical(88),
                            backgroundColor: "#ffffff",
                            borderRadius: CustomStyle.getActualSizeInVertical(44),
                            paddingLeft: CustomStyle.getActualSizeInHorizontal(20),
                            marginLeft: CustomStyle.getActualSizeInHorizontal(100),
                            marginTop: CustomStyle.navBarHeight - 10,
                            flexDirection: 'row',
                            alignItems: 'center',
                            marginRight: CustomStyle.getActualSizeInHorizontal(100),
                        }}
                        >
                            <TextInput style={[CustomStyle.baseText, styles.itemText, {flex: 1,}]}
                                       placeholder={'请输入查询编号'}
                                       placeholderTextColor={'#b2a682'}
                                       value={this.state.searchNum}
                                       textAlign="left"
                                       onSubmitEditing={() => {
                                           Actions.WebViewPage({
                                               url: `http://m.chehangjia.cn/module/appraisaldetail.html?id=${this.state.searchNum}&show=1`
                                           });
                                       }}
                                       onChangeText={(value) => {
                                           this.setState({searchNum: value});
                                       }}
                                       underlineColorAndroid={'#00000000'}/>
                        </View>
                        <TouchableOpacity
                            style={[, {
                                height: CustomStyle.getActualSizeInVertical(95),
                                width: CustomStyle.getActualSizeInHorizontal(260),
                                backgroundColor: '#ffc000',
                                borderRadius: CustomStyle.getActualSizeInHorizontal(34),
                                marginTop: CustomStyle.getActualSizeInVertical(170),
                                marginLeft: CustomStyle.getActualSizeInHorizontal(130),
                                alignItems: 'center',
                                justifyContent: 'center',
                            }]}
                            onPress={() => {
                                Actions.HelpCollectList();
                            }}
                        >
                            <Image source={require('../../../img/helplook/other_bg.png')}
                                   resizeMode={'contain'}
                                   style={{
                                       height: CustomStyle.getActualSizeInVertical(107),
                                       width: CustomStyle.getActualSizeInHorizontal(260),
                                   }}/>
                        </TouchableOpacity>

                    </Image>
                    <View style={[styles.container]}>

                        <CommonText value={this.state.selectArea === null ? '请选择地点' : this.state.selectArea.name}
                                    click={() => {
                                        this.setState({isModalVisible: true});
                                    }}
                        />

                        <TouchableOpacity style={[styles.itemContainer,]} onPress={() => {
                            Actions.BrandRoot({needRequestDetailKind: true, onSelected: this._onCarDetailSelected,});
                        }}>
                            <Text style={[CustomStyle.baseText, styles.itemText, {}]}>{this._getSoldCarInfo()}</Text>
                        </TouchableOpacity>
                        <View style={[styles.itemContainer,]}>
                            <DatePicker
                                mode="date"
                                format="YYYY-MM-DD"
                                date={this.state.date}
                                placeholder='上牌时间'
                                showIcon={false}
                                customStyles={{
                                    dateInput: {
                                        paddingLeft: 0,
                                        alignItems: 'flex-start',
                                        borderWidth: 0,
                                    },
                                    placeholderText: {
                                        fontSize: CustomStyle.getActualFontSize(36),
                                        color: '#b2a682',
                                    },
                                    dateText: {
                                        fontSize: CustomStyle.getActualFontSize(36),
                                        color: '#b2a682',
                                    },
                                    // ... You can check the source to find the other keys.
                                }}
                                onDateChange={(date) => {
                                    this.setState({date: date})
                                }}
                            />
                        </View>

                        <View style={{
                            marginTop: CustomStyle.getActualSizeInVertical(50),
                            marginBottom: CustomStyle.getActualSizeInVertical(30),
                            flexDirection: 'row',
                            paddingLeft: CustomStyle.getActualSizeInHorizontal(20),
                            paddingRight: CustomStyle.getActualSizeInHorizontal(20),
                        }}>
                            <TouchableOpacity style={{
                                height: CustomStyle.getActualSizeInVertical(88),
                                flex: 1,
                                backgroundColor: '#FFc000',
                                alignItems: 'center',
                                justifyContent: 'center',
                                borderRadius: CustomStyle.getActualSizeInVertical(44),
                                alignSelf: 'center',
                                marginRight: CustomStyle.getActualSizeInHorizontal(10),
                            }}
                                              onPress={() => {
                                                  this._subscribe();
                                              }}
                            >
                                <Text style={[CustomStyle.baseText, {
                                    fontSize: CustomStyle.getActualFontSize(36),
                                    color: 'white',
                                }]}>立即预约</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={{
                                height: CustomStyle.getActualSizeInVertical(88),
                                flex: 1,
                                backgroundColor: '#FF7200',
                                alignItems: 'center',
                                justifyContent: 'center',
                                borderRadius: CustomStyle.getActualSizeInVertical(44),
                                alignSelf: 'center',
                                marginLeft: CustomStyle.getActualSizeInHorizontal(10),
                            }}
                                              onPress={() => {
                                                  callPhone("4006161677");
                                              }}
                            >
                                <Text style={[CustomStyle.baseText, {
                                    fontSize: CustomStyle.getActualFontSize(36),
                                    color: 'white',
                                }]}>客户咨询</Text>
                            </TouchableOpacity>
                        </View>


                        <HelpList title='车行家怎么帮您看车' numberTextList={HELP_LIST.concat({
                            number: '08',
                            title: `我们已经帮看车辆 ${this.state.checkedCarOfNumber} 辆`,
                        },)}/>
                        <Button
                            style={{
                                fontSize: CustomStyle.getActualFontSize(30),
                                color: 'white',
                            }}
                            containerStyle={{
                                height: CustomStyle.getActualSizeInVertical(58),
                                width: CustomStyle.getActualSizeInHorizontal(240),
                                backgroundColor: '#ff7200',
                                borderRadius: CustomStyle.getActualSizeInHorizontal(4),
                                alignItems: 'center',
                                justifyContent: 'center',
                                alignSelf: 'center',
                            }}
                            text="服务细则"

                            onPress={() => {
                                Actions.ServerDetail();
                            }}/>
                    </View>
                </ScrollView>
                <TouchableOpacity
                    style={[, {
                        position: 'absolute',
                        left: CustomStyle.getActualSizeInHorizontal(20),
                        top: CustomStyle.navBasePaddingTop + CustomStyle.getActualSizeInVertical(20),
                    }]}
                    onPress={() => {
                        Actions.pop();
                    }}
                >
                    <Image source={require('../../../img/cardetail/back.png')}
                           resizeMode={'contain'}
                           style={{
                               width: CustomStyle.getActualSizeInHorizontal(60),
                               height: CustomStyle.getActualSizeInVertical(60),
                           }}/>
                </TouchableOpacity>
                <TouchableWithoutFeedback onPress={() => {
                    this.setState({isModalVisible: false});
                }}>
                    <Modal isVisible={this.state.isModalVisible}
                           backdropOpacity={0.65}
                           style={{
                               justifyContent: 'flex-end',
                               margin: 0,
                           }}
                    >
                        <AreaSelect
                            selectArea={this.state.selectArea}
                            onPress={(area) => {
                                this.setState({isModalVisible: false, selectArea: area,});
                            }}/>
                    </Modal>
                </TouchableWithoutFeedback>
            </View>
        );
    }


    /*loc	卖车所在地	是	string
     date	上牌时间  yyyy年MM月	是	string
     phone	手机号	是	string
     code	验证码	是	string
     text	车辆信息文本  品牌+车系+车型	是	string	*/
    _subscribe() {
        const {selectArea, date, phone, verifyCode} = this.state;
        if (selectArea && date && phone && verifyCode) {
            const url = Url.BASE_URL + '/com/reservation_info';
            const param = new FormData();
            param.append('type', 3);
            param.append('loc', selectArea.name);
            param.append('date', date);
            param.append('phone', phone);
            param.append('code', verifyCode);
            param.append('text', this._getSoldCarInfo());
            request(url, 'post', param).then(json => {
                this.setState({
                    selectArea: null,
                    date: '',
                    verifyCode: '',
                    requestingVerifyCode: false,
                    carDetail: '',
                });
                Toast.show('预约成功', {
                    duration: Toast.durations.SHORT,
                    position: Toast.positions.CENTER
                });
            }).catch(err => {
                Toast.show(err, {
                    duration: Toast.durations.SHORT,
                    position: Toast.positions.CENTER
                });
            });
        }
    }

    _requestVerifyCode() {
        const url = Url.BASE_URL + '/com/send_verif_code';
        const param = new FormData();
        const {phone} = this.state;
        param.append('phone', phone);
        request(url, 'post', param).then(json => {
            Toast.show('请输入接收到的验证码', {
                duration: Toast.durations.SHORT,
                position: Toast.positions.CENTER
            });
        }).catch(err => {
            Toast.show(err, {
                duration: Toast.durations.SHORT,
                position: Toast.positions.CENTER
            });
        });
    }

    _onCarDetailSelected(brand, series, kind) {
        console.log('SoldCard  ' + `${brand} series ${series} kind ${kind} `);
        this.setState({carDetail: series + kind});
    }

    _fetchHelpLookInfo() {
        const url = Url.BASE_URL + '/jianding/bkcount';
        request(url)
            .then(json => {
                this.setState({checkedCarOfNumber: json.data});
            });
    }
}

class CommonText extends Component {
    static propTypes = {
        value: PropTypes.string,
        click: PropTypes.func,
    };

    render() {
        return (
            <TouchableOpacity style={[styles.itemContainer,]}
                              onPress={() => {
                                  this.props.click();
                              }}
            >
                <Text
                    style={[CustomStyle.baseText, styles.itemText, {}]}>{this.props.value}</Text>
            </TouchableOpacity>
        );
    }
}

class Input extends Component {
    static propTypes = {
        value: PropTypes.string,
        placeholder: PropTypes.string,
        keyboardType: PropTypes.string,
        maxLength: PropTypes.number,
        onChangeText: PropTypes.func,
        click: PropTypes.func,
    };

    render() {
        return (
            <TouchableOpacity
                onPress={() => {
                    this.props.click();
                }}
                style={[styles.itemContainer,]}
            >
                <TextInput style={[CustomStyle.baseText, styles.itemText, {flex: 1,}]}
                           keyboardType={this.props.keyboardType}
                           maxLength={this.props.maxLength}
                           placeholder={this.props.placeholder}
                           placeholderTextColor={'#b2a682'}
                           value={this.props.value}
                           textAlign="left"
                           onChangeText={(value) => {
                               this.props.onChangeText(value);
                           }}
                           underlineColorAndroid={'#00000000'}/>
            </TouchableOpacity>
        );
    }
}


const mapStateToProps = (state) => {
    const {selectArea} = state;
    const {area} = selectArea;
    return {
        selectArea: area,
    };
};

const mapDispatchToProps = (dispatch) => {
    return {};
};


export default connect(mapStateToProps, mapDispatchToProps)(HelpLook);

const styles = StyleSheet.create({
    container: {
        backgroundColor: 'white',
        borderRadius: CustomStyle.getActualSizeInVertical(20),
        marginLeft: CustomStyle.getActualSizeInHorizontal(16),
        marginRight: CustomStyle.getActualSizeInHorizontal(16),
        marginBottom: CustomStyle.getActualSizeInVertical(16),
        paddingBottom: CustomStyle.getActualSizeInVertical(40),
    },
    itemContainer: {
        height: CustomStyle.getActualSizeInVertical(88),
        backgroundColor: '#FFF8D5',
        borderRadius: CustomStyle.getActualSizeInVertical(4),
        marginTop: CustomStyle.getActualSizeInVertical(40),
        flex: 1,
        paddingLeft: CustomStyle.getActualSizeInHorizontal(20),
        marginLeft: CustomStyle.getActualSizeInHorizontal(20),
        flexDirection: 'row',
        alignItems: 'center',
        marginRight: CustomStyle.getActualSizeInHorizontal(20),
    },
    itemText: {
        fontSize: CustomStyle.getActualFontSize(36),
        color: '#b2a682',
    },
});

const HELP_LIST = [
    {
        number: '01',
        title: '怎么联系我',
        content: '1~您直接在帮看服务的首页填写您的资料'
        + '\n2~关注行悦公众号点击帮看项目' +
        '\n3~下载车行家二手车APP点击帮看业务' +
        '\n4~直接拨打400-6161677热线电话'
    },
    {
        number: '02',
        title: '上门看车',
        content: '只要您的车在贵阳贵阳三县一市，我们都可以帮您看您想要了解的车。我们的工作时间是朝十晚五。'
    },
    {
        number: '03',
        title: '153项检测项目',
        content: '其实把车拆分成153个部件，一个一个的认真检查，也就知道车到底怎么回事'
    },
    {
        number: '04',
        title: '让车透明起来',
        content: '有专业的鉴定设备、有统一的鉴定流程，您就会发现车的情况其实没有那么复杂。'
    },
    {
        number: '05',
        title: '火烧、水泡、重大事故',
        content: '什么是火烧、什么是水泡、怎么个重大事故了，我一句一句的和您慢慢说。'
    },
    {
        number: '06',
        title: '买到有问题的车',
        content: '自己不懂、不懂装懂结果就是吃大亏！'
    },
    {
        number: '07',
        title: '错一赔三',
        content: '每个看过的车都会有自己的车况证明，收取帮看服务费399元/台。我们承诺错一赔三，赔付帮看服务费三倍。'
    },
];

